package com.github.defense.plugin.gray.holder;


import com.alibaba.fastjson.JSON;
import com.github.defense.plugin.gray.constants.MetaDataConstant;
import com.github.defense.plugin.gray.decision.predicate.DecisionDefinition;
import com.github.defense.plugin.gray.decision.predicate.PolicyInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: lettger
 * @Date: 2021/6/22 2:00 下午
 */
@Slf4j
public class DecisionDefinitionHolder {

    /**
     * 获取元数据中的灰度决策信息
     * @param list
     * @return
     */
    public static List<DecisionDefinition> getDecisionDefinitions(List<PolicyInfo> list){
        List<DecisionDefinition> definitions = Lists.newArrayList();
        for (PolicyInfo policyInfo : list) {
            for (Map.Entry<String, HashMap> entry : policyInfo.getMetadata().entrySet()) {
                try {
                    HashMap hashMap = entry.getValue();
                    DecisionDefinition definition = new DecisionDefinition();
                    definition.setName((String) hashMap.get(MetaDataConstant.GRAY_DEFINITION_NAME));
                    definition.setInfos(JSON.parseObject(hashMap.get(MetaDataConstant.GRAY_DEFINITION_INFOS).toString(), HashMap.class));
                    definition.setInstance(policyInfo.getInstance());
                    definitions.add(definition);
                }catch (Exception e){
                    log.error("灰度决策格式错误:{}", entry.toString() + "====" + e.getMessage());
                }
            }
        }
        return definitions;
    }


}
